package com.bl.weilan.service.biz.institution.impl;

import com.bl.weilan.common.ApiResponseCode;
import com.bl.weilan.common.CommonServiceException;
import com.bl.weilan.common.utils.ListUtils;
import com.bl.weilan.common.utils.UUIDUtils;
import com.bl.weilan.dao.model.*;
import com.bl.weilan.dao.repository.*;
import com.bl.weilan.service.biz.institution.InstitutionService;
import com.bl.weilan.service.vo.DelBody;
import com.bl.weilan.service.vo.DelListBody;
import com.bl.weilan.service.vo.company.CompanyAddVo;
import com.bl.weilan.service.vo.company.CompanyListVo;
import com.bl.weilan.service.vo.company.CompanyVo;
import com.bl.weilan.service.vo.information.InformationModVo;
import com.bl.weilan.service.vo.informationtype.InformationTypeVo;
import com.bl.weilan.service.vo.institution.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


@Service
@Log4j2
public class InstitutionServiceImpl implements InstitutionService {
    @Autowired
    InstitutionRepository institutionRepository;
    @Autowired
    TradeInstitutionRepository tradeInstitutionRepository;

    @Autowired
    CompanyRepository companyRepository;

    @Autowired
    InstitutionCompanyRepository institutionCompanyRepository;

    @Autowired
    InstitutionTeamRepository institutionTeamRepository;

    @Autowired
    CompanyFinancingRepository companyFinancingRepository;

    @Autowired
    PeopleRepository peopleRepository;

    @Override
    public InstitutionListVo getInstitutionLists(String id,  String type, String order, Pageable pageable ){
        List<InstitutionEntity> institutionEntities = new ArrayList<>();
        InstitutionListVo institutionListVo = new InstitutionListVo();

        List<TradeInstitutionEntity> tradeInstitutionEntities = new ArrayList<>();
        tradeInstitutionEntities = tradeInstitutionRepository.findByTradeId(id);
        if(tradeInstitutionEntities != null) {
            for(TradeInstitutionEntity tradeInsEntity:tradeInstitutionEntities ) {
                String institutionId = tradeInsEntity.getInstitutionId();
                InstitutionEntity institutionEntity = new InstitutionEntity();
                institutionEntity = institutionRepository.findOne(institutionId);
                institutionEntities.add(institutionEntity);
            }
        }
        //手工排序
        if(type.equals("foundTime")) {
            if(order.equals("desc")) { //根据时间降序
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        Date time1 = o1.getFoundTime();
                        Date time2 = o2.getFoundTime();
                        return  time2.compareTo(time1);
                    }
                });
            } else if(order.equals("asc")){ //根据时间升序
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        Date time1 = o1.getFoundTime();
                        Date time2 = o2.getFoundTime();
                        return  time1.compareTo(time2);
                    }
                });
            }

        }  else if(type.equals("total")) { //投资总量
            if(order.equals("desc")) {
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        String total1 = o1.getTotal();
                        String total2 = o2.getTotal();
                        return  total2.compareTo(total1);
                    }
                });
            } else if(order.equals("asc")){
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        String total1 = o1.getTotal();
                        String total2 = o2.getTotal();
                        return  total1.compareTo(total2) ;
                    }
                });
            }

        } else { //投资案例总数
            if(order.equals("desc")) {
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        int num1 = o1.getCaseNum();
                        int num2 = o2.getCaseNum();
                        return num2 - num1;
                    }
                });
            } else {
                institutionEntities.sort(new Comparator<InstitutionEntity>() {
                    @Override
                    public int compare(InstitutionEntity o1, InstitutionEntity o2) {
                        int num1 = o1.getCaseNum();
                        int num2 = o2.getCaseNum();
                        return num1 - num2;
                    }
                });
            }
        }

        //手动分页
        List<InstitutionEntity> institutionEntities1 = new ArrayList<>();
        institutionEntities1 = pageBySubList(institutionEntities, (int)pageable.getPageSize(), (int)pageable.getPageNumber());

        institutionListVo.setTotalCount(institutionEntities.size());
        institutionListVo.setList(institutionEntities1);

        return institutionListVo;
    }

    public static List<InstitutionEntity> pageBySubList(List<InstitutionEntity> list, int pagesize, int curPage) {
        int currentPage = curPage+1;
        List<InstitutionEntity> subList =new ArrayList<>();
        int size=list.size();
        int pageStart = currentPage==1 ? 0 : (currentPage-1) * pagesize;
        int pageEnd = size < currentPage*pagesize ? size : currentPage*pagesize;
        if(size >  pageStart) {
            subList = list.subList(pageStart, pageEnd);
        }
        return subList;
    }


    @Override
    public int getInstitutionNum(String id) {
        List<TradeInstitutionEntity> tradeInstitutionEntities = tradeInstitutionRepository.findByTradeId(id);
        return tradeInstitutionEntities.size();
    }

    @Override
    public InstitutionVo getDetailById(String id) {
        InstitutionVo institutionVo = new InstitutionVo();
        InstitutionEntity institutionEntity = institutionRepository.findOne(id);
        BeanUtils.copyProperties(institutionEntity, institutionVo);

        List<InstitutionTeamVo> institutionTeamVos = new ArrayList<>();
        List<InstitutionTeamEntity> institutionTeamEntities = institutionTeamRepository.findByInstitutionIdOrderByWeight(id);
        for (InstitutionTeamEntity institutionTeamEntity : institutionTeamEntities) {
            InstitutionTeamVo institutionTeamVo = new InstitutionTeamVo();
            BeanUtils.copyProperties(institutionTeamEntity, institutionTeamVo);
            PeopleEntity peopleEntity = peopleRepository.findOne(institutionTeamEntity.getPeopleId());
            institutionTeamVo.setPeopleName(peopleEntity.getName());
            institutionTeamVos.add(institutionTeamVo);
        }
        institutionVo.setInstitutionTeamVos(institutionTeamVos);
        return institutionVo;
    }

    @Override
    public InstitutionListVo getInstitutionLists(String id) {
        List<InstitutionEntity> institutionEntities = new ArrayList<>();;
        InstitutionListVo institutionListVo = new InstitutionListVo();

        List<TradeInstitutionEntity> tradeInstitutionEntities = tradeInstitutionRepository.findByTradeId(id);
        if(tradeInstitutionEntities != null) {
            for(TradeInstitutionEntity tradeInsEntity:tradeInstitutionEntities ) {
                String institutionId = tradeInsEntity.getInstitutionId();
                InstitutionEntity institutionEntity = new InstitutionEntity();
                institutionEntity = institutionRepository.findOne(institutionId);
                institutionEntities.add(institutionEntity);
            }
        }
        institutionListVo.setTotalCount(institutionEntities.size());
        institutionListVo.setList(institutionEntities);

        return institutionListVo;
    }

    @Override
    public InstitutionListVo getAllInstitutionLists(Pageable pageable) {
        Page<InstitutionEntity> institutionEntities;
        InstitutionListVo institutionListVo = new InstitutionListVo();

        institutionEntities = institutionRepository.findAll(pageable);
        institutionListVo.setTotalCount(institutionEntities.getTotalElements());
        institutionListVo.setList(institutionEntities.getContent());

        return institutionListVo;
    }


    @Override
    public InstitutionListVo getInstitutionByName(String name, Pageable pageable) {
        Page<InstitutionEntity> institutionEntities ;
        InstitutionListVo institutionListVo = new InstitutionListVo();

        institutionEntities = institutionRepository.findByNameLike("%"+name+ "%",pageable);
        institutionListVo.setTotalCount(institutionEntities.getTotalElements());
        institutionListVo.setList(institutionEntities.getContent());

        return institutionListVo;
    }

    @Override
    public CompanyListVo getCompanyListVo(String institutionId, Pageable pageable) {
        CompanyListVo companyListVo = new CompanyListVo();
        List<CompanyVo> companyVos = new ArrayList<>();
        Page<InstitutionCompanyEntity> institutionCompanyEntities = institutionCompanyRepository.findByInstitutionIdOrderByTimeDesc(institutionId, pageable);
        for (InstitutionCompanyEntity institutionCompanyEntity : institutionCompanyEntities) {
            CompanyVo companyVo = new CompanyVo();
            CompanyEntity companyEntity = companyRepository.findOne(institutionCompanyEntity.getCompanyId());
            BeanUtils.copyProperties(companyEntity, companyVo);
            List<CompanyFinancingEntity> companyFinancingEntities;
            companyFinancingEntities = companyFinancingRepository.findByCompanyIdOrderByTimeDesc(companyEntity.getId());
//            if (companyFinancingEntities != null){
//                companyOpponentVo.setFinancList(ListUtils.getFirst(companyFinancingEntities));
//            }
            CompanyFinancingEntity companyFinancingEntity = ListUtils.getFirst(companyFinancingEntities);
            companyVo.setRecentFinancing(companyFinancingEntity.getTime());
            companyVo.setRecentRound(companyFinancingEntity.getRounds());
            companyVo.setRecentInvestor(companyFinancingEntity.getInvestor());
            companyVo.setMoney(institutionCompanyEntity.getMoney());
            companyVo.setMoneyString(institutionCompanyEntity.getMoneyString());
            companyVos.add(companyVo);
        }

        companyListVo.setTotalCount(institutionCompanyEntities.getTotalElements());
        companyListVo.setList(companyVos);
        return companyListVo;
    }

    @Override
    public InstitutionTeamListVo getInstitutionTeamListVo(String id, Pageable pageable) {
        InstitutionTeamListVo institutionTeamListVo = new InstitutionTeamListVo();
        List<InstitutionTeamVo> institutionTeamVos = new ArrayList<>();
        Page<InstitutionTeamEntity> institutionTeamEntities = institutionTeamRepository.findByInstitutionIdOrderByWeight(id, pageable);
        for (InstitutionTeamEntity institutionTeamEntity : institutionTeamEntities) {
            InstitutionTeamVo institutionTeamVo = new InstitutionTeamVo();
            BeanUtils.copyProperties(institutionTeamEntity, institutionTeamVo);
            PeopleEntity peopleEntity = peopleRepository.findOne(institutionTeamEntity.getPeopleId());
            institutionTeamVo.setPeopleName(peopleEntity.getName());
            institutionTeamVos.add(institutionTeamVo);
        }
        institutionTeamListVo.setList(institutionTeamVos);
        institutionTeamListVo.setTotalCount(institutionTeamEntities.getTotalElements());
        return institutionTeamListVo;
    }

    @Override
    public void add(InstitutionAddVo institutionAddVo) {
        InstitutionEntity  institutionEntity = new InstitutionEntity();
        institutionEntity.setId(UUIDUtils.getUUID());
        BeanUtils.copyProperties(institutionAddVo, institutionEntity);

        institutionRepository.save(institutionEntity);
    }

    @Override
    public void modify(InstitutionModVo institutionModVo){
        InstitutionEntity institutionEntity = institutionRepository.findOne(institutionModVo.getId());

        if (institutionEntity == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有对应信息");
        }
        BeanUtils.copyProperties(institutionModVo, institutionEntity);
        institutionRepository.save(institutionEntity);
    }

    @Override
    public void del(DelBody id) {
        institutionRepository.delete(id.getId());
    }

    @Override
    public void delList(DelListBody idList) {
        for(String id : idList.getList()) {
            institutionRepository.delete(id);
        }
    }

}
